const userService = require('../service/user.service')
const { NAME_IS_ALREADY_EXISTS, NAME_OR_PASSWORD_IS_REQUIRED } = require('../config/error')
const { md5password } = require('../utils/md5-password')
const verifyUser = async (ctx, next) => {
   // 2.判断用户是否存在
    // 2.1 验证用户名和密码是否为空
    const { name,password } = ctx.request.body
    if(!name || !password) {
      ctx.app.emit('error',NAME_OR_PASSWORD_IS_REQUIRED,ctx)
      return
    }
    // 2.2判断name是否在数据库已经存在了
    const users = await userService.findUserByName(name)
    if(users.length) {
      ctx.app.emit('error', NAME_IS_ALREADY_EXISTS, ctx)
      return
    }

    // 执行下一步
    await next()
}

const handlePassword = async(ctx,next) => {
  // 1.取出密码
  const { password } = ctx.request.body

  // 2.对密码进行加密
  ctx.request.body.password = md5password(password)

  await next()
}

module.exports = {
  verifyUser,
  handlePassword
}